import './FrontStyle.scss'

import {
    FrontStyleFormTheme,
    FrontStyleFormSmallTitle,
    FrontStyleFormScroll,
    FrontStyleFormTable,
    FrontStyleFormTextList
} from './FrontStyleForm'

import { useEventEmitter } from 'ahooks'
import { useState, useMemo } from 'react'
import { Tabs, Space, Tag, Button } from 'antd'
import { CloseOutlined } from '@ant-design/icons'
import { ProTable, TableDropdown } from '@ant-design/pro-components'

import { Encrypt } from '../../Utils/IndexedDB'
import { FormTemplate } from '../../Utils/FormTemp'

// 临时获取图床地址
const url = 'https://image.ljkjkf.com/intellisiteSystem_TieKe/HeYi/'

const TableColumns = [
    {
        dataIndex: 'index',
        valueType: 'indexBorder',
        width: 48,
        fixed: 'left',
    },
    {
        title: '进度',
        dataIndex: 'progress',
        valueType: e => ({ type: 'progress', status: e.state !== 'error' ? 'active' : 'exception' }),
        hideInSearch: true,
        width: 240,
    },
    {
        title: '标题',
        dataIndex: 'title',
        copyable: true,
        ellipsis: true,
        tooltip: '标题过长会自动收缩',
        width: 500
    },
    {
        title: '状态',
        dataIndex: 'state',
        filters: true,
        onFilter: true,
        valueType: 'select',
        valueEnum: {
            default: { text: '待领取...', status: 'default' },
            processing: { text: '解决中...', status: 'processing', disabled: true },
            success: { text: '已解决!', status: 'success' },
            warning: { text: '警报中!', status: 'warning' },
            error: { text: '无法解决!', status: 'error' },
        },
        width: 160
    },
    {
        title: '标签',
        dataIndex: 'labels',
        search: false,
        renderFormItem: (_, { defaultRender }) => { return defaultRender(_) },
        render: (_, record) => (
            <Space>
                {record.labels.map(({ name, color }) => <Tag color={color} key={name}>{name}</Tag>)}
            </Space>
        ),
        width: 160
    },
    {
        title: '创建时间',
        key: 'showTime',
        dataIndex: 'created_at',
        valueType: 'date',
        sorter: true,
        hideInSearch: true,
        width: 160
    },
    {
        title: '创建时间',
        dataIndex: 'created_at',
        valueType: 'dateRange',
        hideInTable: true,
        search: { transform: (value) => ({ startTime: value[0], endTime: value[1] }) },
    },
    {
        title: '操作',
        valueType: 'option',
        key: 'option',
        disable: true,
        align: 'center',
        fixed: 'right',
        width: 120,
        render: () => [
            <Button type='link' key="editable">编辑</Button>,
            <TableDropdown
                key="actionGroup"
                menus={[
                    { key: 'copy', name: '复制' },
                    { key: 'delete', name: '删除' },
                ]}
            />,
        ],
    },
]

const TableData = (num) => {
    const labelsMapping = { 0: 'default', 1: 'processing', 2: 'success', 3: 'warning', 4: 'error' }
    const arr = [...Array(num)].map((_, i) => {
        const labelsData = labelsMapping[Math.floor(Math.random() * 5)]
        return {
            id: i,
            title: `${i + 1} 🐛 [BUG]yarn install命令 antd2.4.5会报错`,
            progress: Math.floor(Math.random() * 100),
            labels: [{ name: labelsData, color: labelsData }],
            locked: false,
            state: labelsData,
            comments: 1,
            created_at: new Date(2024, 0, 1).getTime() + Math.random() * (new Date(2024, 11, 31).getTime() - new Date(2024, 0, 1).getTime()),
        }
    })
    return arr
}

const FrontStyleTheme = ({ data, FormEvent }) => {
    const init = JSON.parse(JSON.stringify(data))
    const ChangeEvent = useEventEmitter()
    const formTemplateProps = useMemo(() => ({
        columns: FrontStyleFormTheme,
        init,
        ModalEvent: FormEvent,
        ChangeEvent,
    }), [FrontStyleFormTheme, init, FormEvent, ChangeEvent])
    const Simulation = () => {
        const [Data, setData] = useState(init)
        ChangeEvent.useSubscription(setData)
        return (
            <div className='StyleSimulation Theme'>
                <img className='ImageBack' src={url + Data.BackUrl} alt="" />
                {Data.NavSwitch && <img className='ImageNav' style={{ height: Data.NavHeight }} src={url + Data.NavUrl} alt="" />}
                {Data.BtmSwitch && <img className='ImageBtm' style={{ height: Data.BtmHeight }} src={url + Data.BtmUrl} alt="" />}
                {Data.LeftSwitch &&
                    <img
                        className='ImageLeft'
                        src={url + Data.LeftUrl}
                        style={{
                            transform: `rotateY(${Data.LeftRotate ? 180 : 0}deg)`,
                            width: Data.LeftWidth + '%',
                            height: Data.LeftHeight + '%',
                            top: Data.LeftTop + '%',
                            left: Data.LeftMargin + '%',
                        }}
                        alt=""
                    />
                }
                {Data.RightSwitch &&
                    <img
                        className='ImageRight'
                        src={url + Data.RightUrl}
                        style={{
                            transform: `rotateY(${Data.RightRotate ? 180 : 0}deg)`,
                            width: Data.RightWidth + '%',
                            height: Data.RightHeight + '%',
                            top: Data.RightTop + '%',
                            right: Data.RightMargin + '%',
                        }}
                        alt=""
                    />
                }
            </div>
        )
    }
    return (
        <div className='StyleTopBox FrontStyleTheme'>
            <Simulation />
            <div className='StyleParameter Theme'>
                <FormTemplate name='Theme' {...formTemplateProps} />
            </div>
        </div>
    )
}
const FrontStyleSmallTitle = ({ data, FormEvent }) => {
    const init = JSON.parse(JSON.stringify(data))
    const ChangeEvent = useEventEmitter()
    const formTemplateProps = useMemo(() => ({
        columns: FrontStyleFormSmallTitle,
        init,
        ModalEvent: FormEvent,
        ChangeEvent,
    }), [FrontStyleFormSmallTitle, init, FormEvent, ChangeEvent])
    const Simulation = () => {
        const [Data, setData] = useState(init)
        ChangeEvent.useSubscription(setData)
        return (
            <div className='StyleSimulation SmallTitle'>
                <div className='SmallTop' style={{ height: Data.titleHeight }}>
                    <div className='ImageClass'>
                        <img src={url + '01.png'} alt="" />
                        <img src={url + '02.png'} alt="" />
                        <img src={url + '03.png'} alt="" />
                    </div>
                    <div
                        className='TitleClass'
                        style={{
                            lineHeight: Data.titleLineHeight + 'px',
                            color: Data.titleFill,
                            fontSize: Data.titleSize,
                            fontFamily: Data.titleFamily,
                            fontWeight: Data.titleWeight,
                            fontStyle: Data.titleStyle,
                            textDecoration: Data.titleUnderline ? 'underline' : 'none',
                            textShadow: `${Data.titleShadowOffsetX} ${Data.titleShadowOffsetY} ${Data.titleShadowBlur} ${Data.titleShadowColor}`,
                            textIndent: Data.titleIndent,
                            letterSpacing: Data.titleSpacing,
                        }}
                    >
                        标题
                    </div>
                    <CloseOutlined
                        className='CloseIcon'
                        style={{
                            fontSize: Data.closeSize,
                            color: Data.closeColor
                        }}
                    />
                </div>
                <div
                    className='SmallRender'
                    style={{ background: `linear-gradient(${Data.renderBackDeg}deg, ${Data.renderBackA01}, ${Data.renderBackA02})` }}
                >
                    渲染区
                </div>
            </div>
        )
    }
    return (
        <div className='StyleTopBox FrontStyleSmallTitle'>
            <Simulation />
            <div className='StyleParameter SmallTitle'>
                <FormTemplate name='SmallTitle' {...formTemplateProps} />
            </div>
        </div>
    )
}
const FrontStyleScroll = ({ data, FormEvent }) => {
    const init = JSON.parse(JSON.stringify(data))
    const ChangeEvent = useEventEmitter()
    const formTemplateProps = useMemo(() => ({
        columns: FrontStyleFormScroll,
        init,
        ModalEvent: FormEvent,
        ChangeEvent,
    }), [FrontStyleFormScroll, init, FormEvent, ChangeEvent])
    const Simulation = () => {
        const [Data, setData] = useState(init)
        ChangeEvent.useSubscription(setData)
        return (
            <div
                className='StyleSimulation Scroll'
                style={{
                    '--scrollSize': Data.scrollSize,
                    '--scrollColor': Data.scrollColor,
                    '--scrollRadius': Data.scrollRadius,
                    '--scrollHover': Data.scrollHover,
                    '--scrollTrack': Data.scrollTrack,
                    '--scrollcorner': Data.scrollcorner,
                }}
            >
                <div>滚动条</div>
            </div>
        )
    }
    return (
        <div className='StyleTopBox FrontStyleScroll'>
            <Simulation />
            <div className='StyleParameter Scroll'>
                <FormTemplate name='Scroll' {...formTemplateProps} />
            </div>
        </div>
    )
}
const FrontStyleTable = ({ data, FormEvent }) => {
    const init = JSON.parse(JSON.stringify(data))
    const ChangeEvent = useEventEmitter()
    const formTemplateProps = useMemo(() => ({
        columns: FrontStyleFormTable,
        init,
        ModalEvent: FormEvent,
        ChangeEvent,
    }), [FrontStyleFormTable, init, FormEvent, ChangeEvent])
    const Simulation = () => {
        const [Data, setData] = useState(init)
        ChangeEvent.useSubscription(setData)
        return (
            <div
                className='StyleSimulation Table'
                style={{
                    '--top_Back': Data.top_Back,
                    '--top_inputDeg': Data.top_inputDeg,
                    '--top_inputColorA01': Data.top_inputColorA01,
                    '--top_inputColorA02': Data.top_inputColorA02,
                    '--top_labelFill': Data.top_labelFill,
                    '--top_labelFamily': Data.top_labelFamily,
                    '--top_labelWeight': Data.top_labelWeight,
                    '--top_labelStyle': Data.top_labelStyle,
                    '--top_labelDeg': Data.top_labelDeg,
                    '--top_labelColorA01': Data.top_labelColorA01,
                    '--top_labelColorA02': Data.top_labelColorA02,
                    '--top_placFill': Data.top_placFill,
                    '--top_textFill': Data.top_textFill,
                    '--top_textFamily': Data.top_textFamily,
                    '--top_textWeight': Data.top_textWeight,
                    '--top_textSize': Data.top_textSize,
                    '--top_textStyle': Data.top_textStyle,
                    '--top_primaryBack': Data.top_primaryBack,
                    '--top_primaryFill': Data.top_primaryFill,
                    '--top_defaultBor': Data.top_defaultBor,
                    '--top_defaultFill': Data.top_defaultFill,
                    '--top_lineBtnFill': Data.top_lineBtnFill,
                    '--top_BtnSize': Data.top_BtnSize,
                    '--top_BtnFamily': Data.top_BtnFamily,
                    '--top_BtnWeight': Data.top_BtnWeight,
                    '--top_BtnStyle': Data.top_BtnStyle,
                    '--btm_Back': Data.btm_Back,
                    '--btm_toolColor': Data.btm_toolColor,
                    '--btm_toolSize': Data.btm_toolSize,
                    '--th_back': Data.th_back,
                    '--th_height': Data.th_height,
                    '--th_color': Data.th_color,
                    '--th_fontSize': Data.th_fontSize,
                    '--th_fontFamily': Data.th_fontFamily,
                    '--th_fontWeight': Data.th_fontWeight,
                    '--th_fontStyle': Data.th_fontStyle,
                    '--td_background': Data.td_background,
                    '--td_color': Data.td_color,
                    '--td_fontSize': Data.td_fontSize,
                    '--td_fontFamily': Data.td_fontFamily,
                    '--td_fontWeight': Data.td_fontWeight,
                    '--td_fontStyle': Data.td_fontStyle,
                    '--td_border_size': Data.td_border_size,
                    '--td_border_type': Data.td_border_type,
                    '--td_border_color': Data.td_border_color,
                    '--td_hover_back': Data.td_hover_back,
                    '--td_hover_color': Data.td_hover_color,
                    '--td_fix_back': Data.td_fix_back,
                    '--td_fix_color': Data.td_fix_color,
                    '--pag_first_color': Data.pag_first_color,
                    '--pag_first_fontSize': Data.pag_first_fontSize,
                    '--pag_first_fontFamily': Data.pag_first_fontFamily,
                    '--pag_first_fontWeight': Data.pag_first_fontWeight,
                    '--pag_first_fontStyle': Data.pag_first_fontStyle,
                    '--pag_li_back': Data.pag_li_back,
                    '--pag_li_color': Data.pag_li_color,
                    '--pag_li_fontSize': Data.pag_li_fontSize,
                    '--pag_li_fontFamily': Data.pag_li_fontFamily,
                    '--pag_li_fontWeight': Data.pag_li_fontWeight,
                    '--pag_li_fontStyle': Data.pag_li_fontStyle,

                    '--pag_hover_back': Data.pag_hover_back,
                    '--pag_hover_color': Data.pag_hover_color,
                    '--pag_hover_border': Data.pag_hover_border,


                }}
            >
                <ProTable
                    rowKey="id"
                    size='lager'
                    columns={TableColumns}
                    request={async () => ({ data: TableData(50), success: true, total: 50 })}
                    options={{ fullScreen: true, setting: true, density: false, reload: true }}
                    scroll={{ x: 600, y: 192 }}
                    search={{
                        layout: 'vertical',
                        showHiddenNum: true,
                        optionRender: (searchConfig, formProps, dom) => [...dom.reverse()]
                    }}
                    pagination={{ pageSize: 5 }}
                />
            </div>
        )
    }
    return (
        <div className='StyleTopBox FrontStyleTable'>
            <Simulation />
            <div className='StyleParameter Table'>
                <FormTemplate {...formTemplateProps} />
            </div>
        </div>
    )
}
const FrontStyleTextList = ({ data, FormEvent }) => {
    const init = JSON.parse(JSON.stringify(data))
    const ChangeEvent = useEventEmitter()
    const formTemplateProps = useMemo(() => ({
        columns: FrontStyleFormTextList,
        init,
        ModalEvent: FormEvent,
        ChangeEvent,
    }), [FrontStyleFormTextList, init, FormEvent, ChangeEvent])
    const Simulation = () => {
        const [Data, setData] = useState(init)
        ChangeEvent.useSubscription(setData)
        return (
            <div className='StyleSimulation TextList'>模拟</div>
        )
    }
    return (
        <div className='StyleTopBox FrontStyleTextList'>
            <Simulation />
            <div className='StyleParameter TextList'>
                <FormTemplate {...formTemplateProps} />
            </div>
        </div>
    )
}

const FrontNavList = ({ data, Theme, FormEvent }) => {
    const init = JSON.parse(JSON.stringify(data))
    const ChangeEvent = useEventEmitter()
    const formTemplateProps = useMemo(() => ({
        columns: FrontStyleFormTextList,
        init,
        ModalEvent: FormEvent,
        ChangeEvent,
    }), [FrontStyleFormTextList, init, FormEvent, ChangeEvent])
    const Simulation = () => {
        const [Data, setData] = useState(init)
        ChangeEvent.useSubscription(setData)
        return (
            <div className='StyleSimulation NavList '>
                <div>

                </div>
            </div>
        )
    }
    return (
        <div className='StyleTopBox FrontStyleTextList'>
            <Simulation />
            <div className='StyleParameter TextList'>
                <FormTemplate {...formTemplateProps} />
            </div>
        </div>
    )
}

const FrontStyle = ({ data: StyleData, ModalEvent }) => {
    const [Active, setActive] = useState(2)

    const FormEvent = useEventEmitter()
    FormEvent.useSubscription(async val => {
        const { type, data } = val
        if (type === 'Added') {
            const { type: itemType } = items.find(v => v.key === Active)
            StyleData[itemType] = data
            console.log('最终数据值', StyleData)
            console.log('保存json文件', await Encrypt(StyleData))
            ModalEvent.emit({ type: 'getStyle' })
            FormEvent.emit({ type: 'offLoading' })
        }
    })
    const items = [
        // { key: 1, type: 'Theme', label: '主题', children: <FrontStyleTheme data={StyleData.Theme} FormEvent={FormEvent} /> },
        // { key: 6, type: 'NavList', label: '导航设置', children: <FrontNavList data={StyleData.TextList} Theme={StyleData.Theme} FormEvent={FormEvent} /> },
        { key: 2, type: 'SmallTitle', label: '小标签', children: <FrontStyleSmallTitle data={StyleData.SmallTitle} FormEvent={FormEvent} /> },
        { key: 3, type: 'Scroll', label: '滚动条', children: <FrontStyleScroll data={StyleData.Scroll} FormEvent={FormEvent} /> },
        { key: 4, type: 'Table', label: '列表页', children: <FrontStyleTable data={StyleData.Table} FormEvent={FormEvent} /> },
        { key: 5, type: 'TextList', label: '文字列表', children: <FrontStyleTextList data={StyleData.TextList} FormEvent={FormEvent} /> },
    ]

    return (
        <div className='FrontStyle'>
            <Tabs tabPosition='left' activeKey={Active} items={items} onChange={setActive} />
        </div>
    );
};

export default FrontStyle;